package com.sunday.volunteer.http;

import android.util.Log;

import com.sunday.common.utils.DeviceUtils;
import com.sunday.common.utils.EncryptUtils;
import com.sunday.common.utils.StringUtils;
import com.sunday.member.converter.GsonConverterFactory;
import com.sunday.member.http.MemberService;
import com.sunday.volunteer.BaseApp;

import java.io.IOException;

import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;

/**
 * Created by Administrator on 2016/1/26.
 */
public class HttpClient {

    private static Retrofit imAdapter;
    private static HttpService httpService;
    private static MemberService memberService;
    //public static String API_URL = "http://112.124.61.23:9996";
    public static String API_URL = "http://volunteeradmin.chinatoplady.cn";

    private static OkHttpClient client;
    static HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();

    public static HttpService getHttpAdapter() {
        if (imAdapter == null) {
            loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
            client = new OkHttpClient.Builder()
                    .addInterceptor(loggingInterceptor)
                    .addInterceptor(new SignInterceptor())
                    .build();
            imAdapter = new Retrofit.Builder()
                    .baseUrl(API_URL)
                    .addConverterFactory(GsonConverterFactory.create())
                    .client(client)
                    .build();
        }
        httpService = imAdapter.create(HttpService.class);
        return httpService;
    }


    public static MemberService getMemberAdapter() {
        if (imAdapter == null) {
            client = new OkHttpClient.Builder()
                    .addInterceptor(loggingInterceptor)
                    .addInterceptor(new SignInterceptor())
                    .build();
            imAdapter = new Retrofit.Builder()
                    .baseUrl(API_URL)
                    .addConverterFactory(GsonConverterFactory.create())
                    .client(client)
                    .build();
        }
        memberService = imAdapter.create(MemberService.class);
        return memberService;
    }


    private static String sign(String nonce, String timestamp) {
        StringBuilder sb = new StringBuilder();
        sb.append("wBH4YJUYIa6a").append(nonce).append(timestamp);
        return EncryptUtils.sha1(sb.toString());

    }

    private static class SignInterceptor implements Interceptor {

        @Override
        public Response intercept(Chain chain) throws IOException {
            Request originalRequest = chain.request();
            if (originalRequest.body() == null || originalRequest.header("Content-Encoding") != null) {
                return chain.proceed(originalRequest);
            }
            String nonce = StringUtils.getRandomString(8);
            String timestamp = String.valueOf(System.currentTimeMillis() / 1000);
            Request compressedRequest = null;
            Log.i("request", originalRequest.url().encodedPath());
            HttpUrl modifiedUrl = originalRequest.url().newBuilder()
                    .addQueryParameter("platform", "android")
                    .addQueryParameter("version", DeviceUtils.getVersion(BaseApp.getInstance().getApplicationContext()))
                    .addQueryParameter("model", android.os.Build.MODEL)
                    .addQueryParameter("os_version", android.os.Build.VERSION.RELEASE)
                    .build();
            compressedRequest = originalRequest.newBuilder().url(modifiedUrl)
                    .header("App-Key", "uwd1c0sxdoyn1")
                    .header("Nonce", nonce)
                    .header("Timestamp", timestamp)
                    .addHeader("Signature", sign(nonce, timestamp))
                    // .cacheControl(CacheControl.FORCE_CACHE)
                    .build();
   /*         //不需要公共参数的接口比如:动态和活动列表
            if(originalRequest.url().encodedPath().equals("/mobile/active/activeList")||
                    originalRequest.url().encodedPath().equals("/mobile/tianjie/member/thirdLogin")||
                    originalRequest.url().encodedPath().equals("/mobile/tianjie/member/thirdregistWithVillage")||
                    originalRequest.url().encodedPath().equals("/mobile/tianjie/member/loginOut")){
                AddPostParamRequestBody newBody = new AddPostParamRequestBody(originalRequest.body(), getParamWithOutMemberId());
                compressedRequest = originalRequest.newBuilder()
                        .header("App-Key", "uwd1c0sxdoyn1")
                        .header("Nonce", nonce)
                        .header("Timestamp", timestamp)
                        .addHeader("Signature", sign(nonce, timestamp))
                        .method(originalRequest.method(), newBody)
                        .build();
            }else{
                AddPostParamRequestBody newBody = new AddPostParamRequestBody(originalRequest.body(), getDeviceInfo());
                compressedRequest = originalRequest.newBuilder()
                        .header("App-Key", "uwd1c0sxdoyn1")
                        .header("Nonce", nonce)
                        .header("Timestamp", timestamp)
                        .header("Cache-Control", String.format("max-age=%d", 60))
                        .addHeader("Signature", sign(nonce, timestamp))
                        .method(originalRequest.method(), newBody)
                        .build();
            }*/
            Response response = chain.proceed(compressedRequest);

            // 无网络时，设置超时为4周
            int maxStale = 60 * 60 * 24 * 28;
            response.newBuilder()
                    .header("Cache-Control", "public, only-if-cached, max-stale=" + maxStale)
                    .removeHeader("nyn")
                    .build();
            return response;
        }
    }

/*    static class AddPostParamRequestBody extends RequestBody {

        final RequestBody body;
        StringBuilder encodedParams = new StringBuilder();

        AddPostParamRequestBody(RequestBody body, HashMap<String, String> params) {
            this.body = body;
            try {
                encodedParams.append('&');
                for (Map.Entry<String, String> entry : params.entrySet()) {
                    encodedParams.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
                    encodedParams.append('=');
                    encodedParams.append(URLEncoder.encode(TextUtils.isEmpty(entry.getValue()) ? "" : entry.getValue(), "UTF-8"));
                    encodedParams.append('&');
                }
            } catch (Exception e) {
                e.printStackTrace();
                Logger.e("param", "参数编码异常");
            }
        }

        @Override
        public long contentLength() throws IOException {
            return body.contentLength() + encodedParams.length();
        }

        @Override
        public MediaType contentType() {
            return body.contentType();
        }

        @Override
        public void writeTo(BufferedSink bufferedSink) throws IOException {
            body.writeTo(bufferedSink);
            bufferedSink.writeString(encodedParams.toString(), Charset.forName("UTF-8"));
        }

    }


    private static HashMap<String, String> getDeviceInfo() {
        HashMap<String, String> maps = new HashMap<>();
        int LoginType= SharePerferenceUtils.getIns(BaseApp.getInstance().getApplicationContext()).getInt(Constants.LOGIN_TYPE,1);
        if(LoginType!=2 && LoginType!=3){
            if(TextUtils.isEmpty(MEMBERID)||MEMBERID.equals("1")){
                MEMBERID = SharePerferenceUtils.getIns(BaseApp.getInstance().getApplicationContext()).getString(Constants.MEMBERID, "1");
            }
            maps.put("memberId", MEMBERID);
        }
        maps.putAll(getParamWithOutMemberId());
        return maps;
    }

    public static String ZONEID;
    public static String MEMBERID;
    private static HashMap<String, String> getParamWithOutMemberId() {
        HashMap<String, String> maps = new HashMap<>();
        maps.put("client", "android");
        if(TextUtils.isEmpty(ZONEID)||ZONEID.equals("-1")){
            ZONEID = SharePerferenceUtils.getIns(BaseApp.getInstance().getApplicationContext()).getString(Constants.ZONEID, "-1");
        }
        maps.put("zoneId", ZONEID);
        maps.put("timestamp", String.valueOf(System.currentTimeMillis()));
        maps.put("model", android.os.Build.MODEL);
        maps.put("os_version", android.os.Build.VERSION.RELEASE);
        if(TextUtils.isEmpty(IMEI)){
            IMEI = DeviceUtils.getIMEI(BaseApp.getInstance().getApplicationContext());
        }
        maps.put("imei", IMEI);
        if(TextUtils.isEmpty(APP_VERSION)&& Build.SDK_INT <23){
            APP_VERSION = DeviceUtils.getIMEI(BaseApp.getInstance().getApplicationContext());
        }
        maps.put("app_version", APP_VERSION);
        return maps;
    }

    private static String IMEI;
    private static String APP_VERSION ;*/

}
